import math
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime, timedelta
import matplotlib.dates as mdates

# 设置字体以支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题


class ShowPassRate:
    def __init__(self):
        self.path = ''
        self.data = {}
        self.p85 = None

    def read_file(self, path):
        self.path = path
        self.get_data()
        self.show()
        self.clear()

    def read_file1(self, path, data_list):
        self.path = path
        self.get_data()
        self.show1(data_list)
        self.clear()

    def show1(self, data_list):
        # 提取数据
        keys = list(self.data.keys())
        # 将时间字符串转换为datetime对象
        times = [datetime.strptime(time, '%H:%M') for time in keys]
        percentage = [d['Percentage'] for d in self.data.values() if 'Percentage' in d]

        plt.plot(times, percentage, marker='o', linestyle='-', color='r', label='通过率')
        # 绘制80%线
        plt.axhline(y=70, color='b', linestyle='--', label='80% Line')

        for i in range(len(data_list)):
            x1_line = data_list[i]['start'].split(' ')[1][:5]
            x2_line = data_list[i]['end'].split(' ')[1][:5]
            x_1 = datetime.strptime(x1_line, '%H:%M')
            x_2 = datetime.strptime(x2_line, '%H:%M')
            # 绘制垂直线
            plt.axvline(x=x_1, color='green', linestyle='--')
            plt.axvline(x=x_2, color='black', linestyle='--')
            # 添加标注
            plt.text(x_1, 1.03, str(data_list[i]['level']), ha='center', va='bottom',
                     transform=plt.gca().get_xaxis_transform())

        # 设置X轴为每1小时一个标记
        ax = plt.gca()  # 获取当前的Axes
        fig = ax.figure
        fig.set_size_inches(20, 12)  # 宽度为10英寸，高度为6英寸
        # ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # 每1小时一个主要刻度
        ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0, 30], interval=1))  # 每半小时一个主要刻度
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # 设置时间格式
        plt.gcf().autofmt_xdate()  # 自动调整X轴日期标签的格式

        # 添加标签和标题
        ax.set_xlabel('时间')
        ax.set_ylabel('通过率（%）')
        name = os.path.basename(self.path).split('_')[0]
        if name == 'car':
            ax.set_title('小客车通过率')
        else:
            ax.set_title('所有车型通过率')
        ax.legend(loc='lower right')

        # # 显示图表
        plt.show()

        # # 保存图表到文件
        # output_dir = os.path.join(os.path.dirname(self.path), 'png1')
        # if not os.path.exists(output_dir):
        #     os.makedirs(output_dir)
        # file_name = os.path.basename(self.path).split('.')[0]
        # output_filename = os.path.join(output_dir, file_name + '.png')
        # plt.savefig(output_filename, dpi=200)
        # # 关闭图表以释放内存
        # plt.close()

    def show(self):
        # 提取数据
        keys = list(self.data.keys())
        # 将时间字符串转换为datetime对象
        times = [datetime.strptime(time, '%H:%M') for time in keys]
        percentage = [d['Percentage'] for d in self.data.values() if 'Percentage' in d]

        # 第一组
        plt.plot(times, percentage, marker='o', linestyle='-', color='r', label='通过率')
        # 绘制85分位数线
        plt.axhline(y=80, color='b', linestyle='--', label='80% Line')

        # 设置X轴为每1小时一个标记
        ax = plt.gca()  # 获取当前的Axes
        fig = ax.figure
        fig.set_size_inches(20, 12)  # 宽度为10英寸，高度为6英寸
        # ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # 每1小时一个主要刻度
        ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0, 60], interval=1))  # 每半小时一个主要刻度
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # 设置时间格式
        plt.gcf().autofmt_xdate()  # 自动调整X轴日期标签的格式

        # 添加标签和标题
        ax.set_xlabel('时间')
        ax.set_ylabel('通过率（%）')
        name = os.path.basename(self.path).split('_')[0]
        if name == 'car':
            ax.set_title('小客车通过率')
        else:
            ax.set_title('所有车型通过率')
        ax.legend(loc='lower right')

        # # 显示图表
        plt.show()

        # # 保存图表到文件
        # output_dir = os.path.join(os.path.dirname(self.path), 'png')
        # if not os.path.exists(output_dir):
        #     os.makedirs(output_dir)
        # file_name = os.path.basename(self.path).split('.')[0]
        # output_filename = os.path.join(output_dir, file_name + '.png')
        # plt.savefig(output_filename, dpi=200)
        # # 关闭图表以释放内存
        # plt.close()

    def get_data(self):
        df_up = pd.read_csv(self.path)
        data0 = df_up.to_dict(orient='records')
        # print(data0)
        self.data = {}
        for i in range(len(data0)):
            time = data0[i]['Group_Time'].split(' ')[1][:5]
            self.data[time] = {
                "Valid_Count": data0[i]['Valid_Count'],
                "Total_Count": data0[i]['Total_Count'],
                "Percentage": data0[i]['Percentage']
            }
        # print(self.data)

    def clear(self):
        self.data.clear()
        self.p85 = None
        self.path = ''


if __name__ == '__main__':

    # A区中度1
    # path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240131\car_time_data.csv'
    # A区重度1
    # path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240207\car_time_data.csv'
    # A区重度2
    # path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240219\car_time_data.csv'
    # A区重度3
    # path = r'D:\GJ\项目\事故检测\output\G004251001000310010,G004251002000610010-20240205\car_time_data.csv'
    # A区轻度1
    # path = r'D:\GJ\项目\事故检测\output\G004251001000310010,G004251002000610010-20240117\car_time_data.csv'
    # 重度
    # path = r'D:\GJ\项目\事故检测\output\G004251001000310010,G004251002000610010-20240330\car_time_data.csv'
    # B区
    # path = r'D:\GJ\项目\事故检测\output\G004251001000210010,G004251001000310010-20240421\car_time_data.csv'
    # path = r'D:\GJ\项目\事故检测\output\G004251001000320010,G004251001000220010-20240502\car_time_data.csv'
    # 其他
    # path = r'D:\GJ\项目\事故检测\output\G004251001000210010,G004251001000310010-20240101\car_time_data.csv'

    # C区
    # path = r'D:\GJ\项目\事故检测\output\G004251001000120020,G004251001000120010-20240416\car_time_data.csv'

    # name = "G004251001000310010,G004251002000610010-20240117"
    name = "G004251002000620010,G004251001000320010-20240207"
    path0 = r'D:\GJ\项目\事故检测\output\邻垫高速'
    # path = os.path.join(path0, name, 'car_pass_rate_data.csv')
    path = os.path.join(path0, name, 'all_pass_rate_data.csv')

    showPassRate = ShowPassRate()
    showPassRate.read_file(path)


